#include "import.h"
#include "ui_import.h"
#include<QtSql/QSqlQuery>
#include<QDebug>
#include<QFile>
#include<QDesktopWidget>
#include<QDate>
#include<QMessageBox>
//This class imports all expense records from the .csv file to the database
Import::Import(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Import)
{
    ui->setupUi(this);

    QRect in=QApplication::desktop()->availableGeometry(this);
    ui->scrollArea->setGeometry(0,0,in.width(),in.height());
    ui->progressBar->setFocus();
    int fontSize=10;
    ui->label->setWordWrap(true);
    ui->progressBar->setVisible(true);
    QAction* backAction = new QAction( tr("Back"), this );
     backAction->setSoftKeyRole( QAction::NegativeSoftKey );
     connect(backAction, SIGNAL(triggered()), this, SLOT(back()));
     addAction( backAction );

    ui->label->setFont(QFont("lucida",(fontSize-1),QFont::Bold,true));
    QMessageBox msg;
    msg.setInformativeText("This will import all expense records from the file C:\\Data\\backup.csv Do you want to continue?");
    msg.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
    msg.setDefaultButton(QMessageBox::Yes);
    int res=msg.exec();
    if(res==QMessageBox::No)
    {
        ui->progressBar->setVisible(false);
         ui->label->setText(tr("No record is exported"));
    }
    else if(res==QMessageBox::Yes)
    {
    db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("finance_db");
    if(!db.open())
    {
        ui->progressBar->setVisible(false);
        ui->label->setText(tr("Error in opening database, can not import records"));
    }
    else
    {
        QString cat;
        int acc,flag=0,amtflag=0,dateflag=0;
        QDate d;
       QSqlQuery q;
       QString line;
       QString amt,note;
       QStringList list;
       QFile f("C:\\backup.csv");

       if(f.open(QIODevice::ReadOnly))
       {
           QTextStream t(&f);
           QTextStream tn(&f);
           double count=0;
           while(!tn.atEnd())
           {
               line=tn.readLine();
               count++;

           }
           f.reset();
           if(count==0)
           {
               ui->progressBar->setVisible(false);
               ui->label->setText(tr("No record is present to import"));
           }
           else
           {
           ui->progressBar->setValue(0);
           int step=ui->progressBar->maximum()/count;
           while(!t.atEnd())
           {
            line=t.readLine();
            list=line.split(',');
            if(list.count()==5)
                note=list[4];
            else
                note="";

            //qDebug()<<line;
            if(q.exec(QString("select * from category_table where category_name='%1'").arg(list[1])))
            {
                if(q.next())
                cat=q.value(0).toString();
                else
                    cat="Unknown";

            if(q.exec(QString("select account_id from account_table where name='%1'").arg(list[0])))
            {
                if(q.next())
                    acc=q.value(0).toInt();
                else
                    acc=0;

              d=QDate::fromString(list[3],"ddd MMM dd yyyy");
              if(d.isNull())
                  d=QDate::fromString(list[3],"ddd MMM d yyyy");
              if(d.isNull())
                  dateflag=1;
              double amount=0;
               amt=list[2];
              try
              {
                  amount=amt.toDouble();
              }
              catch(std::exception &e)
              {
                  amtflag=1;
              }

              if((amtflag==0)&&(dateflag==0)&&(amount>0))
              {
                  qDebug()<<amount;
              q.prepare(QString("insert into expense_table(exp_amt,note,exp_date,acc_id,cat_name) values(?,?,?,?,?)"));
              q.addBindValue(amount);
              q.addBindValue(note);
              q.addBindValue(d);
              q.addBindValue(acc);
              q.addBindValue(cat);
              if(q.exec())
              {
                  qDebug()<<"Inserted";
                  ui->progressBar->setValue(ui->progressBar->value()+step);
                  QSqlQuery qry;
                  if(qry.exec(QString("update account_table set account_amt=account_amt-%1,expense_amt=expense_amt+%2 where account_id=%3").arg(amount).arg(amount).arg(acc)))
                  {
                      qDebug()<<"Account updated";
                  }

              }
              else
              {
                  ui->progressBar->setVisible(false);
                  flag=1;
                  ui->label->setText(tr("Error in databse opening, can not import records"));
              }//Insert query
          }
              else
              {
                  ui->progressBar->setVisible(false);
                  flag=1;
                  ui->label->setText(tr("Error in csv file, can not import records"));
              }//If csv file having invalid fields
          }//Account select query

        }//Category select query

          }//While
           if(flag==0)
           {
               ui->progressBar->setValue(100);
               ui->label->setText(tr("Import process is completed."));
              /* QSqlQuery qy;
               QString name="";
               double budget,expAmt;
               if(qy.exec(QString("select name,budget_amt,expense_amt from account_table")))
              {
                  while(qy.next())
                   {
                  budget=qy.value(1).toDouble();
                  expAmt=qy.value(2).toDouble();
                  qDebug()<<budget;
                  if(budget!=0)//if some budget is assigned
                  {

                      if(expAmt>budget)//IF total expnse amount exceeds budget
                          name=name+qy.value(0).toString()+" ";

                  }//if budget is assigned
              }//While
           }//if select query
            if(name.compare("")!=0)
                   QMessageBox::information(0,"Warning !",QString("Total amount of expenses exceeds budget assigned to accounts :%1").arg(name));
                   */
           }
        }//Count>0
       }//Reading file

       else
       {
           ui->progressBar->setVisible(false);
           ui->label->setText(tr("Error in opening file, can not import records"));
       }
        db.close();
    }//Closing databse
}//Yes to importing
}
Import::~Import()
{
    delete ui;
}

void Import::back()
{
    (new MainWindow)->show();
}
